
package com.rt.schedulenew.utils.checkparam.config;
import java.lang.reflect.Method;
import com.alibaba.fastjson.JSONObject;
import java.util.List;
import java.util.ArrayList;

import com.rt.schedulenew.utils.checkparam.common.BaseUtil;
import org.aspectj.lang.annotation.Around;
import com.rt.schedulenew.utils.global.JsonResultUtil;
import org.springframework.util.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.aspectj.lang.annotation.Aspect;
@Aspect
@Component
public class CheckParamAspect
{
    @Pointcut("execution(public * com.rt..*Controller.*(..)) || execution(public * com.rt.schedulenew.*Controller.*(..)) || execution(public * com.rt..*Api.*(..))")
    public void checkNull() {
    }
    
    @Around("checkNull()")
    public Object check(ProceedingJoinPoint point) throws Throwable {
        String msg = this.doCheck(point);
        if (!StringUtils.isEmpty(msg)) {
            return JsonResultUtil.failure(msg);
        }
        Object obj = point.proceed();
        return obj;
    }
    
    private String doCheck(ProceedingJoinPoint point) {
        Object[] arguments = point.getArgs();
        Method method = BaseUtil.getMethod(point);
        String methodInfo = StringUtils.isEmpty(method.getName()) ? "" : ("  方法名 " + method.getName());
        String msg = "";
        if (BaseUtil.isCheck(method, arguments, Check.class)) {
            Check annotation = method.getAnnotation(Check.class);
            String[] fields = annotation.value();
            Object vo = arguments[0];
            if (vo == null) {
                msg = "param can not be null";
            }
            else {
                List<Object> list = new ArrayList<>();
                if (vo instanceof List) {
                    Object[] array = ((List<?>)vo).toArray();
                    for (Object o : array) {
                        list.add(o);
                    }
                }
                else {
                    list.add(vo);
                }
                for (String field : fields) {
                    try {
                        for (Object o2 : list) {
                            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(o2));
                            if (StringUtils.isEmpty(jsonObject.getString(field))) {
                                return "属性:[" + field + "]不能为空";
                            }
                        }
                    }
                    catch (Exception e) {
                        return "参数解析异常,请使用标准json格式";
                    }
                }
            }
        }
        return msg;
    }
}
